
package com.joysuch.wwyt.dataimport.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/data/import")
@Api(tags = "数据模板导入")
public class DataImportController {

  /* // private static final Logger logger = LoggerFactory.getLogger(BpAccidentController.class);

    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskDistrictEvaluationService riskDistrictEvaluationService;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private MhMonitoringTypeDao monitoringTypeDao;
    @Autowired
    private MhMonitoringPointDao monitoringPointDao;
    @Autowired
    private BpProductionFacilityTypeDao bpProductionFacilityTypeDao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BpProductionFacilityService bpProductionFacilityService;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private MhMajorHazardChemProductDao mhChemProductDao;
    @Autowired
    private MhMajorHazardChemProductRelDao mhMajorHazardChemProductRelDao;
    @Autowired
    private BpStorageTankAreaService storageTankAreaService;
    @Autowired
    private BpStorageTankService storageTankService;
    @Autowired
    private BpIndustrialPipelineService industrialPipelineService;
    @Autowired
    private BpEmergencyContingencyPlanService bpEmergencyContingencyPlanService;
    @Autowired
    private BaseLoginAccountService baseLoginAccountService;
    @Autowired
    private DataImportService dataimportService;

    // private


    *//**
     * 导入风险分区信息
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
     *//*@RequestMapping("import-risk-district-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importRiskDistrictByExcel(MultipartFile file, Long tenentId, String companyCode) {
        List<RiskDistrictBean> jobs = parseRiskDistricts(file);
        for (RiskDistrictBean rb : jobs) {
            rb.setCode(rb.getCode().trim());
            RiskDistrict entity = riskDistrictDao.findByCode(rb.getCode());
            if (entity == null) {
                entity = new RiskDistrict();
                entity.setCode(rb.getCode());
            }
            entity.setName(rb.getName());
            if (rb.getLocation() != null && rb.getLocation().trim().length() > 0) {
                entity.setCoordinates(rb.getLocation().trim());
            }
            riskDistrictDao.save(entity);
        }
        return ResultBean.success("导入成功，共导入" + jobs.size() + "条");
    }*//*
    @RequestMapping("/riskDistrict")
    public Object importRiskDistrictByExcel(MultipartFile file, Long tenentId, String companyCode) {
        List<RiskDistrictBean> jobs = parseRiskDistricts(file);
        for (RiskDistrictBean rb : jobs) {
            rb.setCode(rb.getCode().trim());
            RiskDistrict entity = riskDistrictDao.findByCode(rb.getCode());
            if (entity == null) {
                entity = new RiskDistrict();
                entity.setCode(rb.getCode());
            }
            entity.setName(rb.getName());
            if (rb.getLocation() != null && rb.getLocation().trim().length() > 0) {
                entity.setCoordinates(rb.getLocation().trim());
            }
            riskDistrictDao.save(entity);
        }
        return ResultBean.success("导入成功，共导入" + jobs.size() + "条");
    }

  *//**
     * 导入储罐、储罐区
     *
     * @param file
     * @return
     *//**//*
    @RequestMapping("/tankAndArea")
    @ApiOperation(value = "储罐和储罐区导入")
    public Object importBpStoreTankAndAreaByExcel(MultipartFile file) {
        List<StoreTankAreaBean> areas = parseData(file, 0, StoreTankAreaBean.class, true);
        List<StoreTankBean> tanks = parseData(file, 1, StoreTankBean.class, true);
        int count1 = 0;
        int count2 = 0;
        List<String> errors = new ArrayList<>();
        List<String> err = new ArrayList<>();
        //储罐区导入
        for (int i = 1; i < areas.size(); i++) {
            String areaCode = areas.get(i).getCode();
            String areaName = areas.get(i).getName();
            if (StringUtils.isBlank(areaCode)) {
                logger.error("储罐区第" + areas.get(i).getRowIndex() + "行:储罐区编号不能为空");
                errors.add(logger.toString());
                continue;
            } else if (StringUtils.isBlank(areaName)) {
                logger.error("储罐区第" + areas.get(i).getRowIndex() + "行:储罐区名称不能为空");
                errors.add(logger.toString());
                continue;
            } else if (null != storageTankAreaService.findByCode(areaCode)) {
                logger.error("储罐区第" + areas.get(i).getRowIndex() + "行:该储罐区编码已存在");
                err.add(logger.toString());
                continue;
            }
            try {
                saveStoreTankArea(areas.get(i));
                count1++;
            } catch (Exception e) {
                logger.error("储罐区第" + areas.get(i).getRowIndex() + "行数据异常");
                errors.add(logger.toString());
            }
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        System.out.println(areas);
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        //储罐导入
        for (int i = 1; i < tanks.size(); i++) {
            StoreTankBean tank = tanks.get(i);
            String uniCode = tank.getUniCode();
            if (StringUtils.isBlank(tank.getUniCode())) {
                logger.error("储罐第" + areas.get(i).getRowIndex() + "行:储罐编号不能为空");
                errors.add(logger.toString());
                continue;
            } else if (StringUtils.isBlank(tank.getName())) {
                logger.error("储罐第" + areas.get(i).getRowIndex() + "行:储罐名称不能为空");
                errors.add(logger.toString());
                continue;
            } else if (StringUtils.isBlank(tank.getBelongGroupCode())) {
                logger.error("储罐第" + areas.get(i).getRowIndex() + "行:所属储罐区编码不能为空");
                errors.add(logger.toString());
                continue;
            } else if (StringUtils.isBlank(tank.getBelongGroupName())) {
                logger.error("储罐第" + areas.get(i).getRowIndex() + "行:所属储罐区名称不能为空");
                errors.add(logger.toString());
                continue;
            } else if (null != storageTankService.findByUniCode(uniCode)) {
                logger.error("储罐第" + areas.get(i).getRowIndex() + "行:该储罐编码已存在");
                err.add(logger.toString());
                continue;
            }

            //根据灌区编码查询灌区名称
            String areaCode = tank.getBelongGroupCode();
            BpStorageTankArea byCode = storageTankAreaService.findByCode(areaCode);
            tank.setBelongGroupName(byCode.getName());
            try {
               saveStoreTank(tank);
                count2++;
            } catch (Exception e) {
                logger.error("储罐第" + tank.getRowIndex() + "行数据异常");
                errors.add(logger.toString());
            }
        }
        //拼接错误信息
        StringBuilder stringBuilder = new StringBuilder();
        for (String e : err) {
            stringBuilder.append(e).append(",");
        }
        for (String error : errors) {
            stringBuilder.append(error).append(",");
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        System.out.println(stringBuilder.toString());
        System.out.println("共导入" + areas.size() + tanks.size() + "条数据," +
                "其中:" + "成功导入" + count1 + "个储罐区;" + count2 + "个储罐;" + "失败" + errors.size() + "条;" + "忽略" + err.size() + "条重复数据;" + stringBuilder.toString());
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        return ResultBean.success("成功导入" + count1 + "个储罐区;" + count2 + "个储罐;" + "失败" + errors.size() + "条;"
                + "忽略" + err.size() + "条重复数据;" + stringBuilder.toString());


    }

    *//**//**
     * 保存储罐区
     *
     * @param area
     *//**//*
    private void saveStoreTankArea(StoreTankAreaBean area) {
        BpStorageTankAreaAddBean bean = new BpStorageTankAreaAddBean();
        BeanUtils.copyProperties(area, bean, "rowIndex");
        MhMajorHazard mh = mhMajorHazardDao.findByCode(area.getMajorHazardCode());
        if (mh != null) {
            // Assert.notNull(mh, "重大危险源: " + area.getMajorHazardCode() + "不存在");
            bean.setMhMajorHazard(mh.getId());
        }
        bean.setHasCofferdam(BizUtils.translateChineseToYesNo(bean.getHasCofferdam()));
        bean.setHasFireChannel(BizUtils.translateChineseToYesNo(bean.getHasFireChannel()));
        System.out.println(bean.getHasCofferdam());
        storageTankAreaService.add(bean);
    }

    *//**//**
     * 保存储罐
     *
     * @param tank
     * @throws Exception
     *//**//*
    private void saveStoreTank(StoreTankBean tank) throws Exception {
        translateHasChineseToYesNo(tank);
        BpStorageTankAddBean bean = new BpStorageTankAddBean();
        BeanUtils.copyProperties(tank, bean, "rowIndex");
        MhMajorHazard mh = mhMajorHazardDao.findByCode(tank.getMajorHazardCode());
        if (mh != null) {
            // Assert.notNull(mh, "重大危险源: " + tank.getMajorHazardCode() + "不存在");
            bean.setMhMajorHazard(mh.getId());
        }
        System.err.println(tank.getRowIndex() + ":" + tank.getName());
        // 验证罐区是否存在
        BpStorageTankArea area = storageTankAreaService.findByCode(tank.getBelongGroupCode());
        Assert.notNull(area, "储罐区: " + tank.getBelongGroupCode() + "不存在");
        bean.setUnicode(tank.getUniCode());
        bean.setBpStorageTankArea(area.getId());
        bean.setBpStorageTankAreaName(area.getName());
        bean.setWorkPressureHighRange(new String[]{floatToString(tank.getWorkPressureLowValue()),
                floatToString(tank.getWorkPressureHighValue())});
        bean.setWorkTemperatureRange(new String[]{floatToString(tank.getWorkTemperatureLowValue()),
                floatToString(tank.getWorkTemperatureHighValue())});
        // bean.setHasCofferdam(BizUtils.translateChineseToYesNo(bean.getHasCofferdam()));

        storageTankService.add(bean);
    }
*//*
     *//**
     * 导入应急预案
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
    @RequestMapping("import-emergency-plan-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importEmergencyPlanByExcel(MultipartFile file, @RequestParam(defaultValue = "2020") Integer year,
                                             Long tenentId, String companyCode, int sheetIndex, boolean validate) {
        List<EmergencyPlanBean> areas = parseData(file, sheetIndex, 3, EmergencyPlanBean.class, true);
        List<String> errors = new ArrayList<>();
        for (EmergencyPlanBean area : areas) {
            System.out.println(area.getIndex());
            if (area.getActLevel() == null) {
                continue;
            }
            try {
                saveEmergencyPlan(year, area);
            } catch (Exception e) {
                errors.add("应急预案第" + area.getRowIndex() + "行: " + e.getMessage());
            }
        }
        if (errors.size() > 0) {
            // 抛出异常，终止事务
            throw new RuntimeException(joinString(errors));
        }
        if (validate) {
            // 抛出异常，终止事务。本次导入只为了验证数据，不实际导入
            throw new RuntimeException("数据通过验证，没有错误");
        }
        return ResultBean.success("导入成功，共导入" + areas.size() + "条预案，");
    }

    private void saveEmergencyPlan(int year, EmergencyPlanBean area) throws Exception {

        BpEmergencyContingencyPlanEditBean bean = new BpEmergencyContingencyPlanEditBean();
        bean.setActLevel(area.getActLevel());
        bean.setActMethod(area.getActMethod());
        BpDepart depart = bpDepartDao.findFirstByName(area.getActDepartName());
        if (depart != null) {
            // Assert.notNull(depart, "部门:" + area.getActDepartName() + "不存在");
            bean.setMakeDepartId(depart.getId());
        }
        bean.setName(area.getContent());
        // 演练单位
        bean.setApplicationScope(area.getActDepartName());
        // 演练内容
        bean.setAccidentRiskAnalysis(area.getContent());
        // 备注
        bean.setEmergencyMeasures(area.getCompanyDepartNames());
        if (StringUtils.isNotBlank(area.getActMonth())) {
            setEmegencyPlanTime(year, area.getActMonth(), bean);
        }
        bpEmergencyContingencyPlanService.add(bean);
    }

    private void setEmegencyPlanTime(int year, String actMonth, BpEmergencyContingencyPlanEditBean bean) {
        Pattern p = Pattern.compile("^(\\d+)月");
        Matcher m = p.matcher(actMonth);
        if (m.find()) {
            int month = Integer.parseInt(m.group(1));
            Calendar c = Calendar.getInstance();
            c.set(year, month, 1, 0, 0, 0);
            bean.setMakeTimeStart(c.getTime());
            c.add(Calendar.MONTH, 1);
            c.add(Calendar.DAY_OF_MONTH, -1);
            bean.setMakeTimeEnd(c.getTime());
        }
    }

    private void saveStoreHouse(StoreHouseBean tank) {
        BpStoreHouseAddBean bean = new BpStoreHouseAddBean();
        BeanUtils.copyProperties(tank, bean, "rowIndex");

        MhMajorHazard mh = mhMajorHazardDao.findByCode(tank.getMajorHazardUnitCode());
        Assert.notNull(mh, "重大危险源: " + tank.getMajorHazardUnitCode() + "不存在");
        bean.setMajorHazardId(mh.getId());

        // bpStoreAreaDao

    }

    private void saveStoreArea(StoreAreaBean area) {

    }

    /**
     * 导入工业管道
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
    @RequestMapping("import-bp-industrial-pipeline-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importBpIndustrialPiplelineByExcel(MultipartFile file, Long tenentId, String companyCode,
                                                     boolean validate) {
        List<IndustrialPipeBean> areas = parseData(file, 13, IndustrialPipeBean.class, true);
        List<String> errors = new ArrayList<>();
        for (Iterator iterator = areas.iterator(); iterator.hasNext(); ) {
            IndustrialPipeBean tank = (IndustrialPipeBean) iterator.next();
            try {
                translateHasChineseToYesNo(tank);
                saveIndustrialPipeline(tank);
                System.out.println("共" + areas.size() + "条，完成" + (tank.getRowIndex() - 1) + "条");
            } catch (IllegalArgumentException e) {
                errors.add("工业管道第" + tank.getRowIndex() + "行: " + e.getMessage());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (errors.size() > 0) {
            // 抛出异常，终止事务
            throw new RuntimeException(joinString(errors));
        }
        if (validate) {
            // 抛出异常，终止事务。本次导入只为了验证数据，不实际导入
            throw new RuntimeException("数据通过验证，没有错误");
        }
        return ResultBean.success("导入成功，共导入" + areas.size() + "个储罐区，" + areas.size() + "个储罐");
    }

    // 保存工业管道
    private void saveIndustrialPipeline(IndustrialPipeBean tank) throws Exception {
        BpIndustrialPipelineBean bean = new BpIndustrialPipelineBean();
        BeanUtils.copyProperties(tank, bean, "rowIndex");

        if ("在用".equals(tank.getCurrentState())) {
            bean.setCurrentState(0);
        } else if ("检修".equals(tank.getCurrentState())) {
            bean.setCurrentState(2);
        } else {
            bean.setCurrentState(1);
        }

        MhMajorHazardChemProduct chem = mhChemProductDao.findByName(tank.getHchName());
        if (chem != null) {
            Assert.notNull(chem, "危化品:" + tank.getHchName() + "不存在");
            bean.setHchId(chem.getId());
            bean.setCas(chem.getCasNo());
        }
        bean.setWorkPressureHighRange(new String[]{floatToString(tank.getWorkPressureLowValue()),
                floatToString(tank.getWorkPressureHighValue())});
        bean.setWorkTemperatureRange(new String[]{floatToString(tank.getWorkTemperatureLowValue()),
                floatToString(tank.getWorkTemperatureHighValue())});
        industrialPipelineService.add(bean);
    }

    private String joinString(List<String> errors) {
        StringBuilder sb = new StringBuilder();
        for (String s : errors) {
            sb.append(s).append("\n");
        }
        return sb.toString();
    }

    // 将has开头的文本属性转换为英文字符
    private void translateHasChineseToYesNo(Object tank) throws Exception {

        PropertyDescriptor[] ps = BeanUtils.getPropertyDescriptors(tank.getClass());
        for (PropertyDescriptor pd : ps) {
            if ((pd.getName().startsWith("has") || pd.getName().startsWith("is"))
                    && pd.getPropertyType() == String.class) {
                String value = BizUtils.translateChineseToYesNo((String) pd.getReadMethod().invoke(tank, null));
                pd.getWriteMethod().invoke(tank, value);
            }
        }
    }

    private String floatToString(Float workPressureHighValue) {
        return workPressureHighValue == null ? "" : workPressureHighValue + "";
    }

    *//**
     * 导入风险区域固定评估数据
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     * @throws Exception
     *//*
    @RequestMapping("import-risk-district-stable-evaluation-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importRiskDistrictStableEvaluationByExcel(MultipartFile file, Long tenentId, String companyCode)
            throws Exception {
        List<RiskDistrictStableRiskBean> list = parseData(file, 5, RiskDistrictStableRiskBean.class, true);
        for (RiskDistrictStableRiskBean rb : list) {
            RiskDistrict entity = riskDistrictDao.findByCode(rb.getCode());
            RiskDistrictEvaluation evaluation = new RiskDistrictEvaluation();
            evaluation.setRiskDistrictId(entity.getId());
            evaluation.setEffective(1);
            evaluation.setEvaluationOffice(rb.getEvaluationOffice());
            evaluation.setEvaluationTime(parseStateRiskEvaluationTime(rb.getEvaluationTime()));
            evaluation.setEvaluationUserId(findUserIdByName(rb.getEvaluationUser()));
            evaluation.setStableRiskL(rb.getL());
            evaluation.setStableRiskS(rb.getS());
            evaluation.setStableRiskLevel(calculateStableRiskLevel(rb));
            evaluation.setRiskLevel(evaluation.getStableRiskLevel());
            riskDistrictEvaluationService.add(evaluation);
        }
        return ResultBean.success("导入成功，共导入" + list.size() + "条");
    }

    private Integer calculateStableRiskLevel(RiskDistrictStableRiskBean rb) {
        int l = Integer.parseInt(rb.getL());
        int s = Integer.parseInt(rb.getS());
        int r = l * s;
        if (r < 4) {
            return 4;
        } else if (r < 8) {
            return 3;
        } else if (r < 10) {
            return 2;
        } else {
            return 1;
        }
    }

    private Date parseStateRiskEvaluationTime(String evaluationTime) {
        try {
            return SimpleDateFormatCache.getYmd().parse(evaluationTime);
        } catch (Exception e) {
        }
        return null;
    }

    private Long findUserIdByName(String evaluationUser) {
        BaseUser user = baseUserDao.findFirstByRealName(evaluationUser);
        return user == null ? null : user.getId();
    }

    *//**
     * 导入重大危险源及危化品
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
    @RequestMapping("import-major-hazard-and-hch-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importMajorHazardAndHchByExcel(MultipartFile file, Long tenentId, String companyCode) {
        List<HchBean> hchs = parseData(file, 7, HchBean.class, true);
        int successCount = 0;
        Map<String, MhMajorHazardChemProduct> hchCodeMap = new HashMap<>();
        for (HchBean rb : hchs) {
            if (StringUtils.isBlank(rb.getName())) {
                continue;
            }
            MhMajorHazardChemProduct chem = saveChemistry(rb);
            hchCodeMap.put(rb.getCode(), chem);
            successCount++;
        }

        int facilityCount = 0;
        List<MajorHazardBean> majorHazards = parseData(file, 8, MajorHazardBean.class, true);
        Map<MajorHazardBean, List<MajorHazardHchRelBean>> relationMap = groupMajorHazards(majorHazards);
        for (Entry<MajorHazardBean, List<MajorHazardHchRelBean>> e : relationMap.entrySet()) {
            saveMajorHazard(e, hchCodeMap);
            facilityCount++;
        }

        return ResultBean.success("导入成功，共导入" + successCount + "个危化品," + facilityCount + "重大危险源");
    }

    private void saveMajorHazard(Entry<MajorHazardBean, List<MajorHazardHchRelBean>> e,
                                 Map<String, MhMajorHazardChemProduct> hchCodeMap) {
        MajorHazardBean mh = e.getKey();
        MhMajorHazard majorHazard = mhMajorHazardDao.findByCode(mh.getCode());
        boolean newCreate = false;

        if (majorHazard == null) {
            majorHazard = new MhMajorHazard();
            majorHazard.setCode(mh.getCode());
            newCreate = true;
        }
        majorHazard.setAntiThunderFacilityPeriodlyChecked(
                "是".equals(mh.getAntiThunderDeviceCheckedPeriodly()) ? "Y" : "N");
        majorHazard.setDescription(mh.getDescription());
        majorHazard.setLevel(mh.getLevel());
        majorHazard.setLocation(mh.getLocation());
        majorHazard.setName(mh.getName());
        majorHazard.setRiskDistrictId(findRiskDistrictIdByCode(mh.getRiskDistrictCode()));
        majorHazard.setRvalue(mh.getR());
        majorHazard.setStartUseTime(mh.getInProductionDate());
        majorHazard.setWrittenBy(mh.getCreator());

        mhMajorHazardDao.save(majorHazard);

        if (!newCreate) {
            // 删除已有的关联
            mhMajorHazardChemProductRelDao.deleteByMajorHazardId(majorHazard.getId());
        }

        for (MajorHazardHchRelBean hb : e.getValue()) {
            if (StringUtils.isBlank(hb.getHchCode())) {
                continue;
            }
            MhMajorHazardChemProductRel rel = new MhMajorHazardChemProductRel();
            rel.setMajorHazardId(majorHazard.getId());
            rel.setChemProductFeature(hb.getHchCharacter());// 化学危险性质
            rel.setUsage(hb.getProductionUsage());// 生产用途
            rel.setOperationPressure(hb.getOpPressure());/// 操作压力
            rel.setOperationTemperature(hb.getOpTemprature());// 操作温度
            rel.setDesignStock(hb.getDesignedStorage());// 设计存量
            rel.setStock(hb.getStorage());// 存量
            rel.setCriticalStock(hb.getRestrictLimitStorage());// 临界点
            rel.setSubstanceStatus(hb.getPhysicalState());// 物理状态
            rel.setFixRate(hb.getReviseFactor());// 校证系数
            MhMajorHazardChemProduct hchBean = hchCodeMap.get(hb.getHchCode());
            if (hchBean == null) {
                hchBean = mhChemProductDao.findByCode(hb.getHchCode());
                Assert.notNull(hchBean,
                        "重大危险源[" + mh.getName() + "]关联的危化品[" + hb.getHchCode() + "]不存在,在表格第" + mh.getRowIndex() + "行");
            }
            rel.setMhMajorHazardChemProduct(hchBean);
            mhMajorHazardChemProductRelDao.save(rel);
        }

    }

    private Long findRiskDistrictIdByCode(String riskDistrictCode) {
        RiskDistrict district = riskDistrictDao.findByCode(riskDistrictCode);
        return district == null ? null : district.getId();
    }

    private MhMajorHazardChemProduct saveChemistry(HchBean rb) {
        MhMajorHazardChemProduct p = mhChemProductDao.findByCode(rb.getCode());
        if (p == null) {
            p = new MhMajorHazardChemProduct();
            p.setCode(rb.getCode());
        }
        p.setAlias(rb.getAlias());
        p.setCasNo(rb.getCasNo());
        p.setEngName(rb.getEnName());
        p.setHazardChemicalFlag("是".equals(rb.getKeySupervisorHch()) ? "Y" : "N");
        p.setName(rb.getName());
        p.setType(rb.getDangerType());
        System.out.println(p.getName() + ":" + p.getCasNo());

        mhChemProductDao.save(p);
        return p;
    }

    private Map<MajorHazardBean, List<MajorHazardHchRelBean>> groupMajorHazards(List<MajorHazardBean> majorHazards) {
        Map<MajorHazardBean, List<MajorHazardHchRelBean>> relationMap = new HashMap<>();
        for (MajorHazardBean b : majorHazards) {
            List<MajorHazardHchRelBean> list = relationMap.get(b);
            if (list == null) {
                list = new ArrayList<>();
                relationMap.put(b, list);
            }
            list.add(b.getHchRelBean());
        }
        return relationMap;
    }

    *//**
     * 导入监测点及监测类型及生产装置。
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
    @RequestMapping("import-monitor-point-and-facility-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importMonitoPointAndFacility(MultipartFile file, Long tenentId, String companyCode) {
        List<MonitorPointBean> jobs = parseData(file, 9, MonitorPointBean.class);
        int successCount = 0;
        Map<String, MhMonitoringPoint> pointCodeMap = new HashMap<>();
        for (MonitorPointBean rb : jobs) {
            trimData(rb);
            if (StringUtils.isNotBlank(rb.getCode())) {
                MhMonitoringPoint point = saveMhMonitoringPoint(rb);
                pointCodeMap.put(point.getPointCode(), point);
                successCount++;
            }
        }
        int facilityCount = 0;
        List<ProductionFacilityBean> facilities = parseData(file, 10, ProductionFacilityBean.class);
        for (ProductionFacilityBean p : facilities) {
            trimData(p);
            saveProductionFacility(p, pointCodeMap);
            facilityCount++;
        }

        return ResultBean.success("导入成功，共导入" + successCount + "个监测点," + facilityCount + "个装置");
    }

    private void saveProductionFacility(ProductionFacilityBean p, Map<String, MhMonitoringPoint> pointCodeMap) {
        BpProductionFacilityType type = bpProductionFacilityTypeDao.findByName(p.getType());
        if (type == null) {
            type = new BpProductionFacilityType();
            type.setName(p.getType());
            type.setNumber(0);
            bpProductionFacilityTypeDao.save(type);
        }

        BpProductionFacility facility = bpProductionFacilityDao.findByCode(p.getCode());
        BpProductionAddBean bean = new BpProductionAddBean();
        if (facility != null) {
            bean.setId(facility.getId());
        }
        bean.setName(p.getName());
        bean.setCode(p.getCode());
        bean.setDepartId(findDepardIdByName(p.getDepartName()));
        bean.setEquipmentModel(p.getModelNo());
        bean.setKeyEquipment("是".equals(p.getKeyEquipment()) ? "Y" : "N");
        // bean.setFunctions(p.get);
        bean.setLocation(p.getLocation());
        System.out.println("p.getMajorHazardCode()=" + p.getMajorHazardCode());
        bean.setMajorHazardId(findMajorHazardIdByCode(p.getMajorHazardCode()));
        bean.setProductionAbility(p.getProductionAbility());
        bean.setTechnicalCondition(p.getTechCondition());
        ProductionFacilityStates state = ProductionFacilityStates.findByName(p.getState());
        bean.setState(state == null ? null : state.getId());
        bean.setType(type.getId());
        bean.setMonitorIdss(extractMonitorPointIds(p, pointCodeMap));

        try {
            System.out.println(Arrays.toString(bean.getMonitorIdss()));
            if (facility == null) {
                bpProductionFacilityService.add(bean);
            } else {
                bpProductionFacilityService.update(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Long[] extractMonitorPointIds(ProductionFacilityBean p, Map<String, MhMonitoringPoint> pointCodeMap) {
        String codes = p.getMinitorPointCodes();
        if (StringUtils.isNotBlank(codes)) {
            List<Long> list = new ArrayList<>();
            String[] ss = codes.split("\n");
            for (String s : ss) {
                s = s.trim();
                if (s.length() > 0) {
                    MhMonitoringPoint point = pointCodeMap.get(s);
                    if (point == null) {
                        point = monitoringPointDao.findByPointCode(s);
                    }
                    Assert.notNull(point, "第" + p.getRowIndex() + "行,监测点编号" + s + "对应的监测点不存在，请检查数据后再导入.");
                    list.add(point.getId());
                }
            }
            return list.toArray(new Long[0]);
        }
        return new Long[0];
    }

    private Long findMajorHazardIdByCode(String majorHazardCode) {
        MhMajorHazard mh = mhMajorHazardDao.findByCode(majorHazardCode);
        System.out.println("mh.getId()=" + mh);
        return mh == null ? null : mh.getId();
    }

    private Long findDepardIdByName(String departName) {
        BpDepart depart = bpDepartDao.findFirstByName(departName);
        return depart == null ? null : depart.getId();
    }

    // 保存监测点
    private MhMonitoringPoint saveMhMonitoringPoint(MonitorPointBean rb) {
        MhMonitoringType type = monitoringTypeDao.findFirstByName(rb.getType());
        if (type == null) {
            type = new MhMonitoringType();
            type.setName(rb.getType());
            type.setUnit(rb.getUnit());
            monitoringTypeDao.save(type);
        }
        MhMonitoringPoint point = monitoringPointDao.findByPointCode(rb.getCode());
        if (point == null) {
            point = new MhMonitoringPoint();
            point.setPointCode(rb.getCode());
        }
        point.setName(rb.getName());
        point.setMhMonitoringType(type);
        point.setUnit(rb.getUnit());

        point.setLowValue1(parseDouble(rb.getLevel1a()));
        point.setLowValue2(parseDouble(rb.getLevel1b()));

        point.setHighValue1(parseDouble(rb.getLevel2a()));
        point.setHighValue2(parseDouble(rb.getLevel2b()));

        if ("浓度".equals(rb.getType())) {
            point.setLevel1Threshold(parseDouble(rb.getLevel2a()));
            point.setLevel2Threshold(parseDouble(rb.getLevel2b()));
        } else {
            point.setLevel1Threshold(point.getLowValue1());
            point.setLevel2Threshold(point.getHighValue2());
        }
        monitoringPointDao.save(point);
        return point;
    }

    private Double parseDouble(String level1a) {
        if (StringUtils.isBlank(level1a)) {
            return null;
        }
        return Double.parseDouble(level1a);
    }

    private <T> List<T> parseData(MultipartFile file, int sheetIndex, Class<T> clazz) {
        return parseData(file, sheetIndex, clazz, false);
    }

    private <T> List<T> parseData(MultipartFile file, int sheetIndex, int startRow, Class<T> clazz,
                                  boolean trimStringData) {
        ImportParams params = new ImportParams();
        try {
            params.setStartSheetIndex(sheetIndex);
            params.setHeadRows(startRow);
            params.setTitleRows(0);
            List<T> result = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
            int index = 2;
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clazz, "rowIndex");
            if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) {
                for (T b : result) {
                    propertyDescriptor.getWriteMethod().invoke(b, params.getStartRows() + index);
                    index++;
                }
            }
            if (trimStringData) {
                for (T b : result) {
                    trimData(b);
                }
            }
            return result;
        } catch (Exception e) {
            log.error("parse data exception:", e);
        }
        return null;
    }

    private <T> List<T> parseData(MultipartFile file, int sheetIndex, Class<T> clazz, boolean trimStringData) {
        return parseData(file, sheetIndex, 1, clazz, trimStringData);
    }
*//*
 parseData(file, 11, StoreTankAreaBean.class, true);
 *//*

     *//**
     * 导入风险点及风险点评估历史。
     * 1. 使用风险点名称作为风险点的唯一标识。
     * 2. 使用区域编号作为风险区域的标识，如果风险区域不存在，则忽略此条数据
     *
     * @param file
     * @param tenentId
     * @param companyCode
     * @return
     *//*
    @RequestMapping("import-risk-point-and-evaluation-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importRiskPointAndEvaluationByExcel(MultipartFile file, Long tenentId, String companyCode) {
        List<RiskDistrictControlRiskBean> jobs = parseData(file, 6, RiskDistrictControlRiskBean.class);
        int importCount = 0;
        int ignoreCount = 0;
        for (RiskDistrictControlRiskBean rb : jobs) {
            trimData(rb);
            if ("ignore".equalsIgnoreCase(rb.getRiskPointCode())) {
                // 忽略某些值
                continue;
            }
            RiskPoint point = extractRiskPointInfo(rb);
            if (point != null) {
                importCount++;
                saveSclOrJhaEvaluationInfo(point, rb);
            } else {
                ignoreCount++;
            }
        }
        return ResultBean.success("导入成功，共导入" + importCount + "条,忽略" + ignoreCount + "条");
    }

    *//**
     * 读取类的所有属性，将String类型数据trim后设置回去
     *
     * @param rb
     *//*
    private void trimData(Object rb) {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(rb.getClass());
        for (PropertyDescriptor pd : descriptors) {
            if (pd.getPropertyType() == String.class && pd.getWriteMethod() != null && pd.getReadMethod() != null) {
                try {
                    String value = (String) pd.getReadMethod().invoke(rb, null);
                    if (value != null) {
                        value = value.trim();
                        pd.getWriteMethod().invoke(rb, value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveSclOrJhaEvaluationInfo(RiskPoint point, RiskDistrictControlRiskBean rb) {
        RiskPointTypes type = RiskPointTypes.findByCode(point.getType());
        if (type == RiskPointTypes.JOB_ACTIVITY) {
            saveJhaEvaluation(point, rb);
        } else if (type == RiskPointTypes.DEVICE_FACILITY) {
            saveJhaEvaluation(point, rb);
            // TODO 待开发，暂时无此需求
        }
    }

    private void saveJhaEvaluation(RiskPoint point, RiskDistrictControlRiskBean rb) {
        RiskJhaEvaluationBean bean = new RiskJhaEvaluationBean();
        bean.setAnalyzeTime(parseAnalyzeTime(rb));
        bean.setAnalyzeUserId(parseAnanlyzeUserId(rb));
        bean.setJobId(parseAnalyzeJobId(rb));
        bean.setJobActivity(rb.getJobStep());
        bean.setItems(parseJhaItems(rb));
        bean.setRiskLevel(bean.getItems().get(0).getRiskLevel());
        // riskPointEvaluationJhaService.doEvaluation(point, bean);
        bean.setId(point.getId());
        riskPointService.doJhaEvaluation(bean);
    }

    private List<RiskPointEvaluationJhaItem> parseJhaItems(RiskDistrictControlRiskBean rb) {

        // System.out.println(ToStringBuilder.reflectionToString(rb));

        List<RiskPointEvaluationJhaItem> list = new ArrayList<RiskPointEvaluationJhaItem>(1);
        RiskPointEvaluationJhaItem item = new RiskPointEvaluationJhaItem();
        item.setCheckItem(rb.getCheckItem());
        item.setConsequence(rb.getAccidentTypeAndConsequence());
        item.setControlMethodEmegency(rb.getEmergencyMethod());
        item.setControlMethodManage(rb.getManageMethod());
        item.setControlMethodProtect(rb.getProtectMethod());
        item.setControlMethodTech(rb.getTechMethod());
        item.setControlMethodTrain(rb.getEducationMethod());
        item.setRiskSource(rb.getRiskSourceOrPotentialEvent());

        item.setLikehood(safeParseFloat(rb.getL()));
        item.setExposure(safeParseFloat(rb.getE()));
        item.setConsequenceLevel(safeParseInteger(rb.getC()));
        float d = item.getLikehood() * item.getExposure() * item.getConsequenceLevel();
        item.setDanger(d);
        // <70 低风险
        // 70～159 一般风险
        // 160～319 较大风险
        // >320 重大风险
        if (d < 70) {
            item.setRiskLevel(RiskLevels.DI_FENG_XIAN.getCode());
        } else if (d < 160) {
            item.setRiskLevel(RiskLevels.YI_BAN_FENG_XIAN.getCode());
        } else if (d < 319) {
            item.setRiskLevel(RiskLevels.JIAO_DA_FENG_XIAN.getCode());
        } else {
            item.setRiskLevel(RiskLevels.ZHONG_DA_FENG_XIAN.getCode());
        }
        // item.setDanger(safeParseFloat(rb.getD()));
        // item.setRiskLevel(parseRiskLevel(rb));
        list.add(item);

        return list;
    }

    // 思考后，还是采用严格模式，数据类型不对就报错，要求用户输入高质量的数据，可以减少系统内部潜在的问题
    private Integer safeParseInteger(String c) {
        return Integer.parseInt(c);
    }

    private Float safeParseFloat(String l) {
        return Float.parseFloat(l);
    }

    private Integer parseRiskLevel(RiskDistrictControlRiskBean rb) {
        RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel());
        return riskLevels == null ? null : riskLevels.getCode();
    }

    private Long parseAnalyzeJobId(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getAnalyzeUserJob())) {
            BpJob job = bpJobDao.findByName(rb.getAnalyzeUserJob());
            return job == null ? null : job.getId();
        }
        return null;
    }

    private Long parseAnanlyzeUserId(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getAnalyzeUser())) {
            BaseUser user = baseUserDao.findFirstByRealName(rb.getAnalyzeUser());
            return user == null ? null : user.getId();
        }
        return null;
    }

    private Date parseAnalyzeTime(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getAnalyzeTime())) {
            try {
                return SimpleDateFormatCache.getYmd().parse(rb.getAnalyzeTime());
            } catch (Exception e) {
            }
        }
        return new Date();
    }

    private RiskPoint extractRiskPointInfo(RiskDistrictControlRiskBean rb) {
        RiskDistrict riskDistrict = riskDistrictDao.findByCode(rb.getRiskDistrictCode());
        if (riskDistrict == null) {
            log.warn("风险点: 第" + rb.getRowIndex() + "行，风险区域不存在,忽略此条数据。" + rb.getRiskPointName());
            return null;
        }
        RiskPoint point = riskPointDao.findFirstByName(rb.getRiskPointName());
        if (point == null) {
            point = new RiskPoint();
            point.setName(rb.getRiskPointName());
            if (StringUtils.isNotBlank(rb.getRiskPointCode())) {
                point.setCode(rb.getRiskPointCode());
            } else {
                point.setCode(bizCodeGeneratorFacade.fengXianDian());
            }
            point.setState(0);
        }
        RiskPointTypes types = RiskPointTypes.findByName(rb.getRiskPointType());
        if (types != null) {
            point.setType(types.getCode());

            if (types == RiskPointTypes.DEVICE_FACILITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel2());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            } else if (types == RiskPointTypes.JOB_ACTIVITY) {
                RiskLevels riskLevels = RiskLevels.findByName(rb.getRiskLevel());
                point.setRiskLevel(riskLevels == null ? null : riskLevels.getCode());
            }
        }

        point.setRiskDistrict(riskDistrict);
        point.setStandard(rb.getStandard());
        point.setUnstandardSituationConsequence(rb.getUnstandardSituationAndConsequence());
        point.setAccidentType(rb.getAccidentTypeAndConsequence());
        point.setDescription(rb.getRiskSourceOrPotentialEvent());

        point.setResponsibleDepart(findRiskPointResponsibleDepart(rb));
        point.setResponsibleUser(findRiskPointResponsibleUser(rb));
        ControlLevels controlLevels = ControlLevels.findControlLevelByName(rb.getControlLevel());

        if (controlLevels != null) {
            point.setControlLevelId((long) controlLevels.getCode());
        }
        riskPointDao.save(point);
        return point;
    }

    private BaseUser findRiskPointResponsibleUser(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getResponsibleUserCode())) {
            return baseUserDao.findByCode(rb.getResponsibleUserCode());
        } else if (StringUtils.isNotBlank(rb.getResponsibleUser())) {
            return baseUserDao.findFirstByRealName(rb.getResponsibleUser());
        }
        return null;
    }

    private BpDepart findRiskPointResponsibleDepart(RiskDistrictControlRiskBean rb) {
        if (StringUtils.isNotBlank(rb.getResponsibleDepartCode())) {
            return bpDepartDao.findFirstByCode(rb.getResponsibleDepartCode());
        } else if (StringUtils.isNotBlank(rb.getResponsibleDepart())) {
            return bpDepartDao.findFirstByName(rb.getResponsibleDepart());
        }
        return null;
    }

    private List<RiskDistrictBean> parseRiskDistricts(MultipartFile file) {
        ImportParams params = new ImportParams();
        try {
            params.setStartSheetIndex(4);
            List<RiskDistrictBean> result = ExcelImportUtil.importExcel(file.getInputStream(), RiskDistrictBean.class,
                    params);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/user-job-depart-by-excel")
    @org.springframework.transaction.annotation.Transactional
    public Object importUserJobDepartByExcel(MultipartFile file, Long tenentId, String companyCode, String importTypes,
                                             boolean createLoginAccount, @RequestParam(defaultValue = "123456") String defaultPassword) {
        List<JobBean> jobs = parseData(file, 2, JobBean.class);
        List<BaseUserBean> users = parseData(file, 3, BaseUserBean.class);
        List<DepartBean> departs = parseData(file, 1, DepartBean.class);

        saveJobDepartAndBaseUser(companyCode, jobs, users, departs, createLoginAccount, defaultPassword);
        return ResultBean.success("上传成功");
    }

  *//*  *
     * 部门,岗位.人员导入
     *
     * @param file
     * @return

    @RequestMapping("/userJobDepart")

    public Object importUserJobDepartByExcel(MultipartFile file, String companyCode) {

        List<ExcelDepartBean> departs = parseData(file, 0, ExcelDepartBean.class);
        List<ExcelJobBean> jobs = parseData(file, 1, ExcelJobBean.class);
        List<ExcelUserBean> users = parseData(file, 2,ExcelUserBean.class);
        List<String> errors = new ArrayList<>();
        List<String> err = new ArrayList<>();
        //部门导入
        int count1 = 0;
        for (int i = 1; i < departs.size(); i++) {
            ExcelDepartBean dBean = departs.get(i);
            if (StringUtils.isBlank(dBean.getDepartName())) {
                logger.error("部门" + dBean.getRowIndex() + "行:部门名称不能为空");
                errors.add(logger.toString());
                continue;
            } else if (StringUtils.isBlank(dBean.getParentDepartName())) {
                logger.error("部门" + dBean.getRowIndex() + "行:上级部门名称不能为空");
                errors.add(logger.toString());
                continue;
            } else if (null != bpDepartDao.findSubDepartIdsByCode(dBean.getDepartCode())) {
                logger.error("部门" + dBean.getRowIndex() + "行:部门编号已存在");
                err.add(logger.toString());
                continue;
            }
            dataimportService.saveDepart(dBean);
            count1++;
        }
        //岗位导入
        int count2 = 0;
        for (int i = 1; i <jobs.size() ; i++) {
            ExcelJobBean jBean = jobs.get(i);
            if (StringUtils.isBlank(jBean.getName())){
                logger.error("岗位" +jBean.getRowIndex() + "行:岗位名称不能为空");
                errors.add(logger.toString());
                continue;
            }else if ( null != bpJobDao.findByName(jBean.getName())){
                logger.error("岗位" + jBean.getRowIndex() + "行:部门编号已存在");
                err.add(logger.toString());
                continue;
            }
            dataimportService.saveJob(jBean);
            count2++;
        }
        //人员导入
        int count3 = 0;
        for (int i = 1; i < users.size(); i++) {
            ExcelUserBean uBean = users.get(i);
            if (StringUtils.isBlank(uBean.getRealName())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员姓名不能为空");
                errors.add(logger.toString());
                continue;
            }else if (StringUtils.isBlank(uBean.getRealName())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员身份不能为空");
                errors.add(logger.toString());
                continue;
            }else if (StringUtils.isBlank(uBean.getDepartName())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员部门不能为空");
                errors.add(logger.toString());
                continue;
            }else if (StringUtils.isBlank(uBean.getJobName())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员岗位不能为空");
                errors.add(logger.toString());
                continue;
            }else if (StringUtils.isBlank(uBean.getGender())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员性别不能为空");
                errors.add(logger.toString());
                continue;
            }else if (null != baseUserDao.findByCode(uBean.getCode())){
                logger.error("人员" +uBean.getRowIndex() + "行:人员工号已存在");
                err.add(logger.toString());
                continue;
            }
            dataimportService.saveUser(uBean);
        }
        //saveJobDepartUser(companyCode, jobs, users, departs);
        return ResultBean.success("上传成功");
    }*//*


     *//**
     * 为所有没有登录账号的用户创建登录账号
     *
     * @param tenentId         租户ID
     * @param companyCode      公司代码
     * @param excludeUserCodes 需排除的用户代码
     * @param defaultPassword  默认密码
     * @param validate         测试接口，如果为true，将抛出异常，阻止事务提交
     * @return
     *//*
    @RequestMapping("create-login-account-for-all")
    @org.springframework.transaction.annotation.Transactional
    public Object createLoginAccountForAll(Long tenentId, String companyCode, String excludeUserCodes,
                                           @RequestParam(defaultValue = "123456") String defaultPassword, boolean validate) {
        String[] excludes = null;
        if (StringUtils.isNoneBlank(excludeUserCodes)) {
            excludes = excludeUserCodes.split("\\s*,\\s*");
        }
        int count = dataimportService.batchAddLoginAccountForNoAccountUsers(excludes, defaultPassword);
        if (validate) {
            throw new RuntimeException("添加" + count + "个登录账号, 回滚事务");
        }
        return ResultBean.success("添加" + count + "个登录账号成功");
    }

    private void saveJobDepartAndBaseUser(String companyCode, List<JobBean> jobs, List<BaseUserBean> users,
                                          List<DepartBean> departs, boolean createLoginAccount, String defaultPassword) {
        Map<String, JobBean> jobMap = new HashMap<>();
        Map<String, BaseUserBean> usrCodeMap = new HashMap<>();
        for (JobBean jb : jobs) {
            if (jb.getName() != null && jb.getName().trim().length() > 0) {
                BpJob j = bpJobDao.findByName(jb.getName());
                if (j == null) {
                    j = new BpJob();
                    j.setName(jb.getName());
                      bpJobDao.save(j);
                }
                jb.setJob(j);
                jobMap.put(jb.getName(), jb);
            }
        }

        for (BaseUserBean ub : users) {
            ub.setCode(ub.getCode().trim());
            ub.setCompanyCode(ub.getCompanyCode().trim());
            if (ub.getDepartCode() != null) {
                ub.setDepartCode(ub.getDepartCode().trim());
            }
            if (companyCode.equals(ub.getCompanyCode())) {

                BaseUser bu = baseUserDao.findByCode(ub.getCode());
                if (bu == null) {
                    bu = new BaseUser();
                    bu.setCode(ub.getCode());
                }
                // bu.setNation(ub.getNation());
                bu.setRealName(ub.getRealName());
                JobBean job = jobMap.get(ub.getJobName());
                if (job != null) {
                    bu.setJob(job.getJob().getId());
                } else if (ub.getJobName() != null) {
                    log.warn(ub.getJobName() + "未找到对应的岗位");
                }
                bu.setGender(ub.getGender());
                baseUserDao.save(bu);
                ub.setUser(bu);
                if (createLoginAccount) {
                    // 为用户添加默认账号
                    baseLoginAccountService.createLoginAccountIfNotExists(bu.getId(), bu.getCode(), defaultPassword);
                }
                usrCodeMap.put(bu.getCode(), ub);
            }
        }

        Map<String, DepartBean> departCodeMap = new HashMap<>();

        for (Iterator iterator = departs.iterator(); iterator.hasNext(); ) {
            DepartBean db = (DepartBean) iterator.next();
            db.setCompanyCode(db.getCompanyCode().trim());
            db.setDepartCode(db.getDepartCode().trim());

            if (db.getParentDepartCode() != null) {
                db.setParentDepartCode(db.getParentDepartCode().trim());
            }
            if (db.getChiefCode() != null) {
                db.setChiefCode(db.getChiefCode().trim());
            }
            if (!companyCode.equals(db.getCompanyCode())) {
                continue;
            }
            BpDepart depart = bpDepartDao.findFirstByCode(db.getDepartCode());
            if (depart == null) {
                depart = new BpDepart();
                depart.setCode(db.getDepartCode());
            }
            depart.setName(db.getDepartName());
            depart.setType(DepartType.DEPART);
            if (db.getChiefCode() != null) {
                BaseUserBean chief = usrCodeMap.get(db.getChiefCode());
                if (chief != null) {
                    depart.setChiefId(chief.getUser().getId());
                } else {
                    log.warn("部门:" + db.getDepartName() + "负责人不存在");
                }
            }
            bpDepartDao.save(depart);

            db.setDepart(depart);
            departCodeMap.put(db.getDepartCode(), db);
        }

        // 更新部门信息
        for (BaseUserBean ub : users) {
            if (companyCode.equals(ub.getCompanyCode())) {
                BaseUserBean user = usrCodeMap.get(ub.getCode());
                if (user.getDepartCode() != null) {
                    DepartBean depart = departCodeMap.get(user.getDepartCode());
                    if (depart == null || depart.getDepart() == null) {
                        log.warn("人员:关联部门" + user.getDepartCode() + "不存在");
                    } else {
                        user.getUser().setDepartId(depart.getDepart().getId());
                        baseUserDao.save(user.getUser());
                    }
                }
            }
        }
        // 更新父部门信息
        for (Iterator iterator = departs.iterator(); iterator.hasNext(); ) {
            DepartBean db = (DepartBean) iterator.next();
            if (!companyCode.equals(db.getCompanyCode())) {
                continue;
            }
            if (db.getParentDepartCode() != null) {
                DepartBean parent = departCodeMap.get(db.getParentDepartCode());
                if (parent == null) {
                    // 如果导入的部门在当前导入列表中不存在就去数据库里面找
                    BpDepart parentDepart = bpDepartDao.findFirstByCode(db.getParentDepartCode());
                    if (parentDepart != null) {
                        db.getDepart().setParentId(parentDepart.getId());
                        bpDepartDao.save(db.getDepart());
                    } else {
                        log.warn("父部门:" + db.getParentDepartCode() + "不存在");
                    }
                } else {
                    db.getDepart().setParentId(parent.getDepart().getId());
                    bpDepartDao.save(db.getDepart());
                }
            }
        }

    }*/

}
